package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author wk
 * @create 2021-09-07 19:13
 */
@RestController
@RequestMapping("/api/cart")
public class CartApiController {
    @Autowired
    private CartInfoService cartInfoService;

    @PostMapping("/addCart/{skuId}/{skuNum}")
    public void addCart(@PathVariable Long skuId, @PathVariable Integer skuNum, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        // 测试userId是否已传送
        System.out.println("用户id" + userId);
        System.out.println("临时id" + AuthContextHolder.getUserTempId(request));
        // 购物车微服务需要用户id
        if (StringUtils.isEmpty(userId)) {
            // 如果没有用户id则使用临时用户id
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.addCart(skuId, skuNum, userId);
    }

    @GetMapping("/findCartInfo/{skuId}")
    public CartInfo findCartInfo(@PathVariable Long skuId) {
        return cartInfoService.findCartInfo(skuId);
    }

    // 购物车页面完整路径http://api.gmall.com/api/cart/cartList
    // 获取购物车列表
    @GetMapping("/cartList")
    // 数据的返回根据页面response.data.data
    // 参数 购物车应该携带用户id
    public Result cartList(HttpServletRequest request) {
        // 获取用户id
        String userId = AuthContextHolder.getUserId(request);
        String userTempId = AuthContextHolder.getUserTempId(request);
        List<CartInfo> cartInfoList = cartInfoService.cartList(userId, userTempId);
        return Result.ok(cartInfoList);
    }

    // /api/cart/checkCart/' + skuId + '/' + isChecked
    // 更新购物车商品选中状态
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable Long skuId, @PathVariable Integer isChecked, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(userId)) {
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.checkCart(skuId, isChecked, userId);
        return Result.ok();
    }

    // 查询商品清单信息即 从缓存中查询被选中的商品信息
    @GetMapping("/findCartInfoListByIsChecked")
    public List<CartInfo> findCartInfoListByIsChecked(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        return cartInfoService.findCartInfoListByIsChecked(userId);
    }
}
